package com.buli.blmall.admin.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.net.url.UrlBuilder;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.buli.blmall.admin.common.domain.WxTicket;
import com.buli.blmall.admin.common.domain.WxToken;
import com.buli.blmall.admin.consts.WxConsts;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 微信服务类
 * @author xiang.gao
 * @date 2025/1/14 14:11
 */
@Slf4j
public class WeixinUtil {

    private static Map<String, WxToken> tokenMap = new ConcurrentHashMap<>();
    private static final Lock lock = new ReentrantLock();

    /**
     * 获取微信accessToken
     * @return
     */
    public static String getAccessToken() {
        try {
            WxToken wxToken = tokenMap.get(WxConsts.APP_ID);
            if (wxToken != null && !wxToken.isExpired()) {
                return wxToken.getToken();
            }
            lock.lock();
            try {
                wxToken = tokenMap.get(WxConsts.APP_ID);
                if (wxToken != null && !wxToken.isExpired()) {
                    return wxToken.getToken();
                }

                UrlBuilder tokenUrl = UrlBuilder.ofHttp(WxConsts.WX_TOKEN_URL);
                tokenUrl.addQuery("grant_type", WxConsts.GRANT_TYPE).addQuery("appid", WxConsts.APP_ID).addQuery("secret", WxConsts.APP_SECRET);
                String response = HttpUtil.doGet(tokenUrl.build());
                log.info("获取accessToken, 返回: {}", response);
                JSONObject jsonObject = JSONObject.parseObject(response);
                String token = jsonObject.getString("access_token");
                long expiresIn = jsonObject.getLongValue("expires_in");
                // 提前1分钟过期
                long expireTime = System.currentTimeMillis() + (expiresIn - 60) * 1000;
                tokenMap.put(WxConsts.APP_ID, new WxToken(token, expireTime));
                return token;
            } finally {
                lock.unlock();
            }
        } catch (Exception e) {
            log.error("获取accessToken失败", e);
            return null;
        }
    }

    /**
     * 获取微信ticket
     * @param sceneId
     * @return
     */
    public static WxTicket getWxTicket(String sceneId){
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isBlank(accessToken)) {
                throw new RuntimeException("获取accessToken失败");
            }
            String qrCodeUrl = UrlBuilder.ofHttp(WxConsts.QR_CODE_URL).addQuery("access_token", accessToken).build();
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("expire_seconds", WxConsts.TICKET_EXPIRE_TIME);
            requestBody.put("action_name", "QR_SCENE");
            requestBody.put("action_info", MapUtil.builder("scene", MapUtil.builder("scene_id", sceneId)));
            log.info("获取ticket,url：{}, requestBody：{}", qrCodeUrl, JSON.toJSONString(requestBody));
            log.info("获取ticket,requestBody：{}", JSON.toJSONString(requestBody));
            WxTicket wxTicket = HttpUtil.doJsonPost(qrCodeUrl, requestBody, WxTicket.class);
            log.info("获取ticket,返回:" + wxTicket);
            return wxTicket;
        } catch (Exception e) {
            log.error("获取ticket异常:" + e);
            return null;
        }
    }

    /**
     * 校验微信服务器Token签名
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return boolean
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = {WxConsts.TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder stringBuilder = new StringBuilder();
        for (String param : arr) {
            stringBuilder.append(param);
        }
        String hexString = SHA1(stringBuilder.toString());
        return signature.equals(hexString);
    }

    /**
     * 签名加密
     * @param str
     * @return
     */
    private static String SHA1(String str) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.getBytes());
            return toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字节数组转化为十六进制
     *
     * @param digest 字节数组
     * @return String
     */
    private static String toHexString(byte[] digest) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String shaHex = Integer.toHexString(b & 0xff);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString();
    }

    public static String xml2json(String requestBody) {
        requestBody = StringUtils.trim(requestBody);
        XmlMapper xmlMapper = new XmlMapper();
        JsonNode node;
        try {
            node = xmlMapper.readTree(requestBody.getBytes());
            ObjectMapper jsonMapper = new ObjectMapper();
            return jsonMapper.writeValueAsString(node);
        } catch (Exception e) {
            log.error("xml 2 json error,msg:" + e.getMessage(), e);
        }
        return null;
    }


}
